package main

import (
	"encoding/json"
	"fmt"
	"os"
)

/*
@author: liujun
@file: sanle_shopping.go
@time: 2022/11/18 11:41
*/
//make 方法分配确定内存地址
var user = make(map[string]map[string]interface{})
var car = make(map[string]map[string]interface{})
var user_file = "user.txt"
//存放商品信息
//{"F001":{"name":"apple","price":"9"},
// "F002":{"name":"banana","price":"3"}}
var products = map[string]map[string]interface{}{
	"F001":{"name":"apple","price":9},
	"F002":{"name":"banana","price":3}}
func main() {
	//存放用户信息 {"sc":{"passwd":"123456","money":"300"}}
	//var usermessage = make(map[string]interface{})
	//usermessage["passwd"]="123456"
	//usermessage["money"]=10
	//user["sc"]=usermessage
	init_user()
	//执行用户信息初始化函数
	fmt.Println("欢迎来到三乐购物系统")
	for {
		fmt.Println("1.登录")
		fmt.Println("2.注册")
		var option string
		fmt.Print("请输入你的选择(按q退出)：")
		fmt.Scan(&option)
		switch option {
		case "1" :
			var name string
			var passwd string
			fmt.Print("请输入用户名：")
			fmt.Scan(&name)
			//Read := bufio.NewReader(os.Stdin)
			//name, _ := Read.ReadString('\n')
			fmt.Print("请输入密码：")
			//passRead := bufio.NewReader(os.Stdin)
			//passwd, _ := passRead.ReadString('\n')
			fmt.Scan(&passwd)
			result := login(name,passwd)
			if result {
				fmt.Println("登录成功")
				for {
					menu()
					var op string
					fmt.Print("请输入你的选择：")
					fmt.Scan(&op)
					switch op {
					case "1":
						show_goods(products)
					case "2":
						var product_id string
						fmt.Print("请输入添加到购物车的商品编号：")
						fmt.Scan(&product_id)
						_, ok := products[product_id]
						if ok {
							var nums int
							fmt.Print("请输入需要购买的数量:：")
							fmt.Scan(&nums)
							add_car(name, product_id,nums)
						}
					case "3":
						checkout(name)
					case "4":
						os.Exit(3)
					}

				}
			} else {
				fmt.Println("用户名不存在或密码错误")
			}
		case "2" :
			var name string
			var passwd string
			for {
				fmt.Print("请输入用户名：")
				fmt.Scan(&name)
				//Read := bufio.NewReader(os.Stdin)
				//name, _ := Read.ReadString('\n')
				fmt.Print("请输入密码：")
				fmt.Scan(&passwd)
				//passRead := bufio.NewReader(os.Stdin)
				//passwd, _ := passRead.ReadString('\n')
				result := regist(name, passwd)
				if result {
					fmt.Println(user)
					os.Exit(3)
				}
			}
		case "q" :
			os.Exit(3)
		default:
			fmt.Println("输入不合法")
		}
	}
}
//从文件中读取信息 初始化user
func init_user()  {
	content, err := os.ReadFile(user_file) // 只读方式打开文件
	if err != nil {
		fmt.Println("初始化用户信息失败，没有指定文件")
	}else {
		err1 := json.Unmarshal(content, &user)
		if err1 != nil {
			fmt.Println("json格式化失败，初始化用户信息失败！")
		}
	}
}

func login(name string,passwd string) bool {
	_, ok := user[name]
	if ok && user[name]["passwd"]==passwd{
		return true
	}else {
		return false
	}
}
func regist(name string,passwd string) bool {
	_, ok := user[name]
	if ok {
		fmt.Println("用户已存在，请重新输入")
		return false
	} else {
		var money int
		fmt.Print("请输入你的充值金额：")
		fmt.Scan(&money)
		var usermessage = map[string]interface{}{
			"passwd":passwd,
			"money":money}
		user[name] = usermessage
		fmt.Println("将用户信息写入文件....")
		WriteUserInfo()
		return true
	}
}
func menu()  {
	fmt.Println("1、查看商品列表")
	fmt.Println("2、添加到购物车")
	fmt.Println("3、结算")
	fmt.Println("4、退出")
}
func show_goods(products map[string]map[string]interface{})  {
	fmt.Printf("%-10s%-10s%-10s\n","Code","Item","Price")
	for k,v := range products{
		fmt.Printf("%-10s%-10s%-10d\n",k,v["name"],v["price"])
	}
}

func WriteUserInfo()  {
	file, err := os.OpenFile(user_file,os.O_CREATE|os.O_WRONLY,666)
	if err != nil {
		fmt.Println("打开文件， 写入用户信息失败！")
	}else {
		str_user, _ :=json.Marshal(user)
		file.Write(str_user)
		fmt.Println("写入用户信息成功")
	}
}

func add_car(name string, product_id string, nums int) {
	_, ok := car[name][product_id]
	if ok {
		n1 := int(car[name][product_id].(int64))
		nums = nums + n1
		car[name] = map[string]interface{}{
			product_id:nums}
	} else {
		car[name] = map[string]interface{}{
			product_id:nums}
	}
}

func checkout(name string) {
	m1 := int(user[name]["money"].(float64))
	car_list := car[name]
	//{"F001": 2,"F002":3}
	total := 0
	fmt.Printf("%-10s%-10s%-10s%-10s%-10s\n","No","Name","Price","Num","Total")
	for k,v := range car_list{
		pro_name := products[k]["name"]
		price := products[k]["price"].(int)
		pro_total := price * v.(int)
		total = total +pro_total
		fmt.Printf("%-10s%-10s%-10d%-10d%-10d\n",k,pro_name,price,v,pro_total)
	}
	fmt.Println("所有商品总价为：",total)
	if m1 >= total {
		m1 = m1-total
	}else {
		fmt.Println("余额不足！")
	}
	user[name]["money"] = m1
	fmt.Println(user[name])
	fmt.Println("将用户信息写入文件....")
	WriteUserInfo()

}